package net.mihome.app.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.bean.Tweet;
import net.mihome.app.bean.TweetList;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.UIHelper;
import net.mihome.app.ui.view.MihomeBigPaperView;
import net.mihome.app.ui.view.MyViewLinster;
import net.mihome.app.ui.view.WeatherView;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.PreferenceUtils;
import net.mihome.app.utils.RequestParamsFactory;

import org.apache.http.Header;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by ZHAO on 2014/12/29 0029.
 */
public class DazibaoFragment extends Fragment {
    static DazibaoFragment instance;
    private MihomeBigPaperView mihomeBigPaperView;
    private WeatherView weatherView;
    private View dazibaoMyButton ;
    private View mHeadPub_tweet;
    private TextView weatherTitle;
    private TextView weatherTime;
    private TextView weatherCount;
    private TextView weatherTip;
    private String nowCity="";
    private ImageLoader imageLoader;
//    private View xuanfuCloseView;
    private View xuanfuWindowView;
    //
    private TextView dazibaoUnreadCountTv;
    private TextView dazibaoXuanfuContent;
    private ImageView dazibaoXuanfuAvatarIv;
    private View unreadView;
    //
    //
//    private ListViewTweetAdapter adapter;
    private List<Tweet> listData = new ArrayList<Tweet>();
    private int begin=0;
    private int num=10;
    private int bigPaperType= TweetList.CATALOG_LASTEST;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mainView= inflater.inflate(R.layout.frame_dazibao2,null,false);
        mihomeBigPaperView= (MihomeBigPaperView) mainView.findViewById(R.id.dazibao_view);
        weatherTitle= (TextView) mainView.findViewById(R.id.im_weather_title);
        weatherView= (WeatherView) mainView.findViewById(R.id.weahter_view_id);
        weatherTime= (TextView) mainView.findViewById(R.id.im_weather_time);
        weatherCount= (TextView) mainView.findViewById(R.id.im_weather_count);
        weatherTip= (TextView) mainView.findViewById(R.id.im_weather_count);
        imageLoader=ImageLoader.getInstance();

        //大字报提示
        dazibaoUnreadCountTv= (TextView) mainView.findViewById(R.id.dazibao_unread_count);
        dazibaoXuanfuAvatarIv= (ImageView) mainView.findViewById(R.id.dazibao_xuanfu_avatar);
        dazibaoXuanfuContent= (TextView) mainView.findViewById(R.id.dazibao_xuanfu_content);
        dazibaoUnreadCountTv.setText("0");

        chageWeatherBg();
        xuanfuWindowView=mainView.findViewById(R.id.xuanfu_windows_view);
        xuanfuWindowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(getActivity(),BigpaperLetterActivity.class);
                startActivity(intent);
            }
        });
        mHeadPub_tweet =  mainView.findViewById(R.id.mihome_pub_dazibao2);
        mHeadPub_tweet.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                UIHelper.showTweetPub(getActivity());
            }
        });

        weatherView.initWeather();
        nowCity=PreferenceUtils.getPrefString(AppContext.getInstance(),"weather_city", "杭州");
        mihomeBigPaperView.setMyViewLinster(new MyViewLinster() {
            @Override
            public void onLoadComplete() {
                checkLetter();
                refreshUnread();
            }

            @Override
            public void onBeforeLoad() {

            }
        });
        unreadView=mainView.findViewById(R.id.unread_view);
        unreadView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Long lastBigpaperId=AppContext.getInstance().getLastBigpaper();
                if(lastBigpaperId!=null){
                    mihomeBigPaperView.redirtoUnread(lastBigpaperId);
                }else{
                    Toast.makeText(getActivity(),"没有未读大字报",Toast.LENGTH_SHORT).show();
                }
            }
        });
//        DataBean dataBean=null;
//        if(savedInstanceState!=null){
//            dataBean=(DataBean) savedInstanceState.getSerializable("list_data");
//        }
//        if(dataBean!=null){
//            //如果有先前保存的数据,则加载先前的数据
//            mihomeBigPaperView.setListData(dataBean.getData());
//            mihomeBigPaperView.adapter.notifyDataSetChanged();
//        }else{
//            //如果没有，则加载数据
            mihomeBigPaperView.init();
//        }
        return mainView;
    }

    public static DazibaoFragment newInstance(){
        if(instance==null){
            instance=new DazibaoFragment();
        }
        return instance;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try{
            mihomeBigPaperView.currentPage(requestCode);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        String city=PreferenceUtils.getPrefString(AppContext.getInstance(),"weather_city", "杭州");
        if(!nowCity.equals(city)&&weatherView!=null){
            weatherView.initWeather();
        }
//        mihomeBigPaperView.currentPage();
        checkLetter();
        refreshUnread();
        super.onResume();
    }
    /**
     * 根据当前时间判断是否hi白天还是晚上
     * */
    @SuppressLint("NewApi")
    public void chageWeatherBg(){
        try{
            int hour=Integer.parseInt(new SimpleDateFormat("HH").format(new Date()));
            if(hour>19||hour<7){
                weatherView.setBackground(getResources().getDrawable(R.drawable.weather_wegit_bg_night));
                weatherTitle.setTextColor(getResources().getColor(R.color.white));
                weatherTime.setTextColor(getResources().getColor(R.color.white));
                weatherCount.setTextColor(getResources().getColor(R.color.white));
                weatherTip.setTextColor(getResources().getColor(R.color.white));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 更新系统提示
     * */
    public void checkLetter(){
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        AppContext.ASYNC_HTTP_CLIENT.get(getActivity(), URLs.MIHOME_GET_BIGPAPER_COUNT,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                if(responsePojo.getData()!=null){
                    Double unReadNum= (Double) responsePojo.getData().get("unread_count");
                    if(responsePojo.getData().get("send_user")!=null){
                        User user=User.parse((Map) responsePojo.getData().get("send_user"));
                        if(user!=null){
                            imageLoader.displayImage(user.getFace(),dazibaoXuanfuAvatarIv);
                        }
                    }
                    if(unReadNum!=null&&unReadNum>0){
                        xuanfuWindowView.setVisibility(View.VISIBLE);
                        dazibaoXuanfuContent.setText("您有"+unReadNum.intValue()+"条消息未读");
                    }else{
                        xuanfuWindowView.setVisibility(View.GONE);
                    }
                }else{
                    xuanfuWindowView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                String msg="获取消息时发生错误";
                if(arg3!=null&&arg3.getMessage()!=null){
                    msg=msg+":"+arg3.getMessage();
                }
                Toast.makeText(getActivity(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }
    /**
     * 访问服务器，由服务器计算出用户有多少条未读消息，并将结果显示在ui上
     * */
    public void refreshUnread(){
        Long lastBigpaperId=AppContext.getInstance().getLastBigpaper();
        RequestParams requestParams=RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("last_bigpaper_id",lastBigpaperId);
        AppContext.ASYNC_HTTP_CLIENT.get(getActivity(),URLs.MIHOME_GET_BIGPAPER_UNREAD_COUNT,requestParams,new MiAsyncHttpResponseHandler<Double>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Double> responsePojo) {
                Double unReadSum=responsePojo.getData();
                int unReadCount=unReadSum.intValue();
                if(unReadCount>0){
                    dazibaoUnreadCountTv.setVisibility(View.VISIBLE);
                    dazibaoUnreadCountTv.setText(unReadCount+"");
                }else{
                    dazibaoUnreadCountTv.setVisibility(View.GONE);
                }
            }
            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                dazibaoUnreadCountTv.setVisibility(View.GONE);
                Toast.makeText(getActivity(),arg3.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
//        if(mihomeBigPaperView!=null){
//            DataBean dataBean=new DataBean();
//            dataBean.setData(mihomeBigPaperView.getListData());
//            outState.putSerializable("list_data",dataBean);
//        }
    }
    class DataBean implements Serializable {
        private List data;

        public List getData() {
            return data;
        }

        public void setData(List data) {
            this.data = data;
        }
    }
}
